import { defineStore } from "pinia";
import { userLogin } from "@/api/user";
import LocalCache from "@/utils/cache";
import router from "@/router";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore("userInfo", {
  state: () => ({
    userInfos: {
      accessToken: "",
    },
  }),
  actions: {
    async setUserInfos() {
      if (LocalCache.getCache("userInfo")) {
        this.userInfos = LocalCache.getCache("userInfo");
      }
    },
    async getUserInfo(user: { account; password }, isRemember) {
      const res = await userLogin(user);
      if (res.code !== 200) {
        return Snackbar.error(res.msg);
      }
      if (isRemember) {
        LocalCache.setCache("account", user.account);
        LocalCache.setCache("password", user.password);
      }
      LocalCache.setCache("token", res.data.authInfo.accessToken);
      LocalCache.setCache("userInfo", res.data.authInfo);
      router.push({
        path: "/activity",
      });
    },
  },
});
